package cn.spy.threaddownload.thread;

import cn.spy.threaddownload.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class DownloadTask implements Runnable {
    // 计数器
    private CountDownLatch cdl;
    // 查询连接
    private String url;
    // 单个文件大小
    private int partFileSize;
    // 整个文件大小
    private int contentLength;
    // 当前文件所属的标号
    private int partNum;
    // 文件一共多少部分数
    private int filePartSum;
    // 临时文件夹
    private String tempDir;


    public DownloadTask(CountDownLatch cdl, String url,
                        int partFileSize, int contentLength, int partNum,
                        int filePartSum, String tempDir) {
        this.cdl = cdl;
        this.url = url;
        this.partFileSize = partFileSize;
        this.contentLength = contentLength;
        this.partNum = partNum;
        this.filePartSum = filePartSum;
        this.tempDir = tempDir;
    }

    @Override
    public void run() {
        this.doTask();
    }

    public void doTask() {
        try {
            HttpURLConnection connection = HttpUtils.getUrlConnection(url);
            connection.setConnectTimeout(10000);
            connection.setRequestMethod("GET");
            if (partNum == filePartSum - 1) {
                int start = partNum * partFileSize;
                connection.setRequestProperty("RANGE", "bytes=" + start + "-");
                log.info("下载的分片区间 " + start + " - all");
            } else {
                int start = partNum * partFileSize;
                int end = (partNum + 1) * partFileSize - 1;
                connection.setRequestProperty("RANGE",
                        "bytes=" + start + "-" + end);
                log.info("下载的分片区间 " + start + " - " + end);
            }

            InputStream is = connection.getInputStream();
            RandomAccessFile raf =
                    new RandomAccessFile(tempDir + File.separator + partNum,"rw");
            byte[] dataArr = new byte[contentLength];
            int len = -1;

            while ((len = is.read(dataArr)) != -1) {
                raf.write(dataArr, 0 , len);
            }

            raf.close();
            is.close();
            connection.disconnect();
            log.info("================ " + partNum + " 部分文件下载成功");
            cdl.countDown();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
